package org.byqh.dqeai.util;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;
import java.util.Base64;

/**
 * @author flythink
 */
public class TripleDesUtils {
    private static final Charset CHAR_ENCODING = Charset.forName("UTF-8");
    private static final String CRYPT_ALGORITHM = "DESede";
    private static final String PADDING = "desede/CBC/PKCS5Padding";

    static {
        //Security.addProvider(new BouncyCastleProvider());
    }

    /**
     * 24-byte
     */
    private static final byte[] MY_KEY = "9oquil2oo2vb63e8ionujny6".getBytes(CHAR_ENCODING);

    /**
     * 8-byte
     */
    private static final byte[] MY_IV = "9oco1v52".getBytes(CHAR_ENCODING);

    public static String encode(String text) {

        if (text == null) {
            return null;
        }

        String retVal = null;

        try {

            final SecretKeySpec secretKeySpec = new SecretKeySpec(MY_KEY, CRYPT_ALGORITHM);

            final IvParameterSpec iv = new IvParameterSpec(MY_IV);

            final Cipher cipher = Cipher.getInstance(PADDING);

            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, iv);

            final byte[] encrypted = cipher.doFinal(text.getBytes(CHAR_ENCODING));

            retVal = Base64.getMimeEncoder().encodeToString(encrypted);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return retVal;
    }

    public static String decode(String text) {
        if (text == null) {
            return null;
        }

        String retVal = null;

        try {

            final SecretKeySpec secretKeySpec = new SecretKeySpec(MY_KEY, CRYPT_ALGORITHM);
            final IvParameterSpec iv = new IvParameterSpec(MY_IV);

            final Cipher cipher = Cipher.getInstance(PADDING);

            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, iv);

            final byte[] decrypted = cipher.doFinal(Base64.getMimeDecoder().decode(text.getBytes(CHAR_ENCODING)));

            retVal = new String(decrypted, CHAR_ENCODING);
        } catch (Exception e) {

            e.printStackTrace();
        }

        return retVal;
    }

    private static String pkcs7padding(String data) {
        int bs = 16;
        int padding = bs - (data.length() % bs);
        String padding_text = "";
        for (int i = 0; i < padding; i++) {
            padding_text += (char) padding;
        }
        return data + padding_text;
    }
}
